(function(){

	//var script = document.createElement("script");
  //script.src = "//fbo-bookmarklet.googlecode.com/git/scripts/lib/bootstrap.js";  
  //document.getElementsByTagName("head")[0].appendChild(script);
  
  var myCss = document.createElement("link");
  myCss.setAttribute("rel", "stylesheet");
  myCss.setAttribute("type", "text/css");
  myCss.setAttribute("href", "//fbo-bookmarklet.googlecode.com/git/css/my-bootstrap.css");		
  document.getElementsByTagName("head")[0].appendChild(myCss);
  
  var myCss = document.createElement("link");
  myCss.setAttribute("rel", "stylesheet");
  myCss.setAttribute("type", "text/css");
  myCss.setAttribute("media", "all");
  myCss.setAttribute("href", "//fbo-bookmarklet.googlecode.com/git/css/addthisevent.css");		
  document.getElementsByTagName("head")[0].appendChild(myCss);
  
  var myCss = document.createElement("link");
  myCss.setAttribute("rel", "stylesheet");
  myCss.setAttribute("type", "text/css");
  myCss.setAttribute("href", "//fbo-bookmarklet.googlecode.com/git/css/main.css");		
  document.getElementsByTagName("head")[0].appendChild(myCss);

	var v = "1.9.1";
  if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
		var done = false;
		var script = document.createElement("script");
		script.src = "//ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
		script.onload = script.onreadystatechange = function(){
			if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
				done = true;
				initMyBookmarklet();
			}
		};
		document.getElementsByTagName("head")[0].appendChild(script);
		
	} else {
		initMyBookmarklet();
	}
	
	removeFBOMain = function() {
    $("#my-fbo-main").fadeIn(1000);
    setTimeout("$('#my-fbo-main').remove()", 750);
	}
	
	function initMyBookmarklet() {
    
    var script = document.createElement("script");
    script.src = "//fbo-bookmarklet.googlecode.com/git/scripts/lib/atemay.js"; 
    script.onload = script.onreadystatechange = function(){
			if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete") {
        addthisevent.settings({
          license		: 'aao8iuet5zp9iqw5sm9z',
          mouse		: true,
          css			: true,
          outlook		: {show:true, text:'Outlook Calendar'},
          google		: {show:true, text:'Google Calendar'},
          yahoo		: {show:true, text:'Yahoo Calendar'},
          ical		: {show:true, text:'iCal Calendar'},
          facebook	: {show:false, text:'Facebook Event'}
        });
        addthisevent.refresh();
			}
		}; 
    document.getElementsByTagName("head")[0].appendChild(script);
    
    (window.myBookmarklet = function() {
			if ($("#my-fbo-main") == null || $("#my-fbo-main").length == 0) {
          $("body").append("\
            <div id=my-fbo-main>\
              <div id=my-add-reminder>\
                <a href='http://www.fbozone.com' title='Add to Calendar' class='addthisevent'>\
                  Add to Calendar\
                  <span id=my-event-link class='_url'>http://www.fbozone.com</span>\
                  <span id=my-event-startdate class='_start'>10-05-2012</span>\
                  <span id=my-event-enddate class='_end'>11-05-2012</span>\
                  <span class='_zonecode'>15</span>\
                  <span id=my-event-title class='_summary'>n/a</span>\
                  <span id=my-event-description class='_description'>n/a</span>\
                  <span id=my-event-location class='_location'>http://www.fbozone.com</span>\
                  <span id=my-event-organizer class='_organizer'>FBO Zone</span>\
                  <span class='_organizer_email'>support@fbozone.com</span>\
                  <span class='_all_day_event'>true</span>\
                  <span class='_date_format'>DD/MM/YYYY</span>\
                </a>\
              </div>\
              <div>\
              <form class=form-horizontal>\
                <div id=my-header class=row>\
                  <div id=my-agency-logo class=span2></div/>\
                  <div class=span=10>\
                    <p id=my-agency-title></p/>\
                    <div id=my-agency-name></div>\
                  </div>\
                </div>\
                \
                <div class=control-group>\
                  <label class=control-label for=my-to-email-addresses>To:</label>\
                  <div class=controls>\
                    <input id=my-to-email-addresses type=text class=span7>\
                  </div>\
                </div>\
                \
                <div class=control-group>\
                  <label class=control-label for=my-solicitation-number>Solicitation Number:</label>\
                  <div class=controls>\
                    <input id=my-solicitation-number type=text class=span7>\
                  </div>\
                </div>\
                \
                <div class=control-group>\
                  <label class=control-label for=my-response-date>Response Date:</label>\
                  <div class=controls>\
                    <input id=my-response-date type=text class=span7>\
                  </div>\
                </div>\
                \
                <div class=control-group>\
                  <label class=control-label for=my-notes>Notes:</label>\
                  <div class=controls>\
                    <textarea id=my-notes rows=3 class=span7></textarea>\
                  </div>\
                </div>\
                \
              <div>\
                <div id=my-email type=submit class=btn btn-small>Send Email</div>\
                <div id=my-close type=button class=btn btn-small>Close</div>\
              </div>\
              \
           </form>\
           </div>\
          </div>");
			} else {
				removeFBOMain();
			}
		})();
		
		getData = function(fob_selector) {
      if($(fob_selector) != null && $(fob_selector).length > 0) {
        return $.trim($(fob_selector).eq(0).text());
      } 
      else {
         return 'N/A';
      }
		}
		
		getInputData = function(fob_selector) {
      if($(fob_selector) != null && $(fob_selector).length > 0) {
        return $.trim($(fob_selector).eq(0).val());
      } 
      else {
         return 'N/A';
      }
		}
		
		populateData = function(my_selector, fob_selector, field_name) {
      data = getData(fob_selector);
      $(my_selector).val(data);
		}
		
		populateEventData = function() {
      $('#my-event-link').text(document.location.href);
      $('#my-event-location').text(document.location.href);
      //$('#my-event-startdate').text(new Date());
      //$('#my-event-enddate').text(getData('#dnf_class_values_procurement_notice__response_deadline__widget'));
      $('#my-event-title').text($('.agency-header h2').text());
      $('#my-event-description').text($('.sol-num').text().trim());
		}
		
		populateEventData();
		
		$('#my-agency-logo').html($('.agency-logo').html());
		$('#my-agency-title').text($('.agency-header h2').text());
		$('#my-agency-name').html($('.agency-name').html());
		$('#my-solicitation-number').val($('.sol-num').text().replace('Solicitation Number:', '').trim());
		
		$('#my-sidebar-related-notices')
      .val("Number of change notices: " + $('ul#sb_related_notices li:contains("Changed")').length);
		
		populateData(
      '#my-response-date', 
      '#dnf_class_values_procurement_notice__response_deadline__widget', 
      'responseDate');
		
		$('#my-close').click(function() {
      setTimeout("$('#my-fbo-main').remove()", 750);
    });
		
		$('#my-email').click(function() {
		
      myData = {
        toEmails: getInputData('#my-to-email-addresses').split(','),
        image: $('.agency-logo').html(),
        title: $('.agency-header h2').text(),
        agencyName: $('.agency-name').html(),
        solicitationNumber: $('.sol-num').text().replace('Solicitation Number:', '').trim(),
        responseDate: getData('#dnf_class_values_procurement_notice__response_deadline__widget'),
        notes: getInputData('#my-notes'),
        sourceUrl: $('a.bkmrk.permalink').attr('href')
      }
      
      $.ajax({
        type: 'POST',
        url: 'https://win5007.smarterasp.net/jcolletti91-001/fbozone/beta911/Opportunities/new',
        beforeSend: function(xhr) {
          xhr.setRequestHeader( "Content-type", "application/json" );
        },
        data: JSON.stringify(myData),	
        dataType: 'json',
        success: function(data) {
          alert('successfully posted data!' + data);
        }
      });
      
      removeFBOMain();
		});
	}

})();